import sys
import requests, json
from util.log_handle import LogHandle
from util.json_handle import JSONHandle

# article_api = 'https://www.98api.cn/api/ArtRandom.php'
# resp = requests.get(article_api) # 请求网址拿到json格式的文章数据
# data = json.loads(resp.text) # json解析出来
# title = data['title'] # 取出标题
# author = data['author'] # 取出作者
# content = data['content'] # 取出内容
# content = content.replace('<p>','').replace('</p>','').replace('\n','\n\n')
# # 剔除内容中p的开始和结尾标签，然后将\n换成\n\n，达到分段的作用
# md = f"# {title}\n\n##### 作者:{author} \n\n{content} " # 将标题、作者、内容填入字符串，作为发送的内容部分
# print(md)
class DINGDINGRobot():
    jsonHandle = JSONHandle()
    logHandle = LogHandle()

    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=336c1f1fed433d8e5e9acc6460be1f361b37699ac10614ab37d12d970ac556dc'
    headers = {
        'Content-Type':'application/json',
    }
    sourcePath = "../../config/message.json"
    defalut_message = ""

    def _Init_(self, webhook, sourcePath):
        self.webhook = webhook
        self.defalut_message = self.jsonHandle.read_json_file(sourcePath)

    def MesaagsePost(self, type, info):
        for data in self.defalut_message["sourceData"]:
            if type == data["type"]:
                info = data["data"]
                break
        resp = requests.post(self.webhook, headers=self.headers, data=json.dumps(info))
        print(resp.text)
  
    def MesaagseTextPost(self, info, message):
        for data in self.defalut_message["sourceData"]:
            if "text" == data["type"]:
                info = data["data"]
                break
        info["text"]["content"] = message
        resp = requests.post(self.webhook, headers=self.headers, data=json.dumps(info))
        print(resp.text)

if __name__ == "__main__":
    sourcePath = "../../config/message.json"
    robot = DINGDINGRobot(sourcePath)
    info = []
    if len(sys.argv) <= 1:
        print(f'please input command by this way. Ctrl+C to exit')
        help()
    robot.MesaagseTextPost(info, sys.argv[1])